//
//  ClickRightCornerJumpToViewController.m
//  NewChat
//
//  Created by lanou3g on 16/2/29.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "ClickRightCornerJumpToViewController.h"
#import "UIView+SDAutoLayout.h"
#import "TopicTableViewCell.h"
#import "LReplyTableViewCell.h"
#import "ReplyViewController.h"
#import "PersonalHomePageTableViewController.h"
#import "MHDataHelper.h"
#import "SKXRongCloudManager.h"

@interface ClickRightCornerJumpToViewController ()

//用来设置导航栏
@property (nonatomic, strong)UISegmentedControl *segment;

//用来记录当前选择的segment的下标
@property (nonatomic, assign)NSUInteger index;

//存放用户的所有主题
@property (nonatomic, strong)NSMutableArray *topicArray;

//存放用户的所有回复
@property (nonatomic, strong)NSMutableArray *replayArray;

//存放我的收藏
@property (nonatomic, strong)NSMutableArray *myCollectArray;

//设置背景图
@property (nonatomic, strong)UIImageView *backgroundView;

@end



@implementation ClickRightCornerJumpToViewController

#pragma --------- 懒加载 ------------
- (NSMutableArray *)topicArray{
    
    if (!_topicArray) {
        
        _topicArray = [NSMutableArray array];
    }
    return _topicArray;
}

- (NSMutableArray *)replayArray{
    
    if (!_replayArray) {
        _replayArray = [NSMutableArray array];
    }
    
    return _replayArray;
}

- (NSMutableArray *)myCollectArray{
    if (!_myCollectArray) {
        _myCollectArray = [NSMutableArray array];
    }
    return _myCollectArray;
}


- (instancetype)initWithStyle:(UITableViewStyle)style{
    
    if (self = [super initWithStyle:UITableViewStylePlain]) {
        
    }
    return self;
}

#pragma -----请求数据--------------
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    //隐藏底部tabbar
    self.tabBarController.tabBar.hidden = YES;
    
    NSLog(@"这个页面是ClickRightCornerJumpToViewController");
    //判断网络状态
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    
    //如果没有网络（不请求数据）
    if (status == RealStatusNotReachable) {
        
        
    }else{

        //请求数据
        [[MHDataHelper shareDataHelper] requestAllHerTopicWith:[AVUser currentUser].objectId didFinished:^(NSMutableArray *array) {
            
            self.topicArray = array;
            [self.tableView reloadData];
        }];
        
        [[MHDataHelper shareDataHelper] requestAllHerReplysWith:[AVUser currentUser].objectId didFinished:^(NSMutableArray *array) {
            
            self.replayArray = array;
            [self.tableView reloadData];
        }];

        AVQuery *query = [FindModel query];
        [query includeKey:@"owner"];
        [query includeKey:@"collected"];
        [query whereKey:@"collected" containedIn:@[[AVUser currentUser]]];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

            if (objects.count != 0) {
                self.myCollectArray = [NSMutableArray arrayWithArray:objects];
                [self.tableView reloadData];
            }
            
        }];

    }

}

//cell的标示符
static NSString *identifier = @"LReplyCell";


- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"这个页面是ClickRightCornerJumpToViewController");

    //注册cell
    [self.tableView registerClass:[TopicTableViewCell class] forCellReuseIdentifier:@"TCell"];
    UINib *replyNib = [UINib nibWithNibName:@"LReplyTableViewCell" bundle:[NSBundle mainBundle]];
    [self.tableView registerNib:replyNib forCellReuseIdentifier:identifier];

    //segment显示的标题
    NSArray *string = @[@"主题",@"收藏",@"回复"];
    self.segment = [[UISegmentedControl alloc]initWithItems:string];

    //设置默认选中的下标
    self.segment.selectedSegmentIndex = 0;
    
    //设置选中的状态
    self.segment.momentary = NO;
    
    //设置高和宽
    self.segment.sd_layout.heightIs(35).widthIs([UIScreen mainScreen].bounds.size.width*0.6);
    
    self.segment.multipleTouchEnabled = YES;
    self.navigationItem.titleView = self.segment;
    
    //给segment添加事件
    [self.segment addTarget:self action:@selector(clickSegmentControlAction:) forControlEvents:UIControlEventValueChanged];
    
    //添加背景图
    [self addBackgroundPicture];
}

//添加背景图片
- (void)addBackgroundPicture{
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blue.jpg"]];

    self.tableView.mj_header =  [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh)];
}

//下拉刷新
-(void)tableViewRefresh{
        RealReachability *reachability = [RealReachability sharedInstance];
        ReachabilityStatus status = [reachability currentReachabilityStatus];
        if (status == RealStatusNotReachable) {
    
        }else{//有网
    
    
    //刷新时根据下标请求不同数据
    if (self.segment.selectedSegmentIndex == 0) {
        
        [[MHDataHelper shareDataHelper] requestAllHerTopicWith:[AVUser currentUser].objectId didFinished:^(NSMutableArray *array) {
            if (self.topicArray.count) {
                [self.topicArray removeAllObjects];
            }
            self.topicArray = array;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                [self.tableView.mj_header endRefreshing];
            });
        }];
        
    }else if (self.segment.selectedSegmentIndex == 1){
        
        AVQuery *query = [FindModel query];
        
        [query includeKey:@"owner"];
        [query includeKey:@"collected"];
        [query whereKey:@"collected" containedIn:@[[AVUser currentUser]]];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            self.myCollectArray = [NSMutableArray arrayWithArray:objects];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            
        }];
        
    }else{
        
        [[MHDataHelper shareDataHelper] requestAllHerReplysWith:[AVUser currentUser].objectId didFinished:^(NSMutableArray *array) {
            if (self.replayArray.count) {
                [self.replayArray removeAllObjects];
            }
            self.replayArray = array;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                [self.tableView.mj_header endRefreshing];
            });
        }];
    }
        }//有网
}

//点击segment时根据下标刷新数据
- (void)clickSegmentControlAction:(UISegmentedControl*)sender{
    //将当前segment的下标赋给index，用于根据不同segment创建不同的cell
    self.index = sender.selectedSegmentIndex;
    [self.tableView reloadData];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
//分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    //根据当前segment的下标返回不同的行数
    
    if (self.segment.selectedSegmentIndex == 2) {
        
        return self.replayArray.count;
        
    }else if (self.segment.selectedSegmentIndex == 1){
        
        return self.myCollectArray.count;
        
    }else{
        
        return self.topicArray.count;
    }
    
    
}

//创建cell并赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        //根据 当前segment的下标 加载对应的cell
         if (self.segment.selectedSegmentIndex == 2){
        
                LReplyTableViewCell *lreplyCell = [tableView dequeueReusableCellWithIdentifier:identifier];
                    
                [lreplyCell.userBtn addTarget:self action:@selector(ClickUserPictureBtn:) forControlEvents:(UIControlEventTouchUpInside)];
                     
                lreplyCell.userBtn.tag = indexPath.row + 2001;
             ReplyModel *replyModel = nil;
             if (self.replayArray.count) {
                 replyModel  = self.replayArray[self.replayArray.count-1-indexPath.row];
             }
             
                [lreplyCell configureCellWithReplyModel:replyModel];
                     
                lreplyCell.voiceBtn.tag = indexPath.row + 2001;
                     
                [lreplyCell.voiceBtn addTarget:self action:@selector(voiceBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
                     
                lreplyCell.selectionStyle = UITableViewCellSelectionStyleNone;
             
             lreplyCell.voiceBtn.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"btncolor.jpg"]];
            return lreplyCell;
             
         }else if (self.segment.selectedSegmentIndex == 1){
             
                TopicTableViewCell *Topcell = [tableView dequeueReusableCellWithIdentifier:@"TCell"];

                Topcell = [[TopicTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TCell"];

                [Topcell.userPictureBtn addTarget:self action:@selector(ClickUserPictureBtn:) forControlEvents:(UIControlEventTouchUpInside)];
                Topcell.userPictureBtn.tag = indexPath.row+501;

             FindModel *findModel = nil;
             if (self.myCollectArray.count) {
                 findModel = self.myCollectArray[self.myCollectArray.count-1-indexPath.row];
             }

                [Topcell configureCellWithModel:findModel];

                Topcell.voiceBtn.tag = indexPath.row+501;
                [Topcell.voiceBtn addTarget:self action:@selector(voiceBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
             
             Topcell.voiceBtn.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"btncolor.jpg"]];
             return Topcell;
             
         }else{

                TopicTableViewCell *Topcell = [tableView dequeueReusableCellWithIdentifier:@"TCell"];

                Topcell = [[TopicTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TCell"];
                 
                 
                [Topcell.userPictureBtn addTarget:self action:@selector(ClickUserPictureBtn:) forControlEvents:(UIControlEventTouchUpInside)];
                 
                Topcell.userPictureBtn.tag = indexPath.row + 1001;
             FindModel *findModel = nil;
             if (self.topicArray.count) {
                 findModel = self.topicArray[self.topicArray.count-1-indexPath.row];
             }
                 
                 [Topcell configureCellWithModel:findModel];

                 Topcell.voiceBtn.tag = indexPath.row + 1001;

                 [Topcell.voiceBtn addTarget:self action:@selector(voiceBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
             Topcell.voiceBtn.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"btncolor.jpg"]];
            return Topcell;

     }
    
}

//点击时 播放语音
- (void)voiceBtnAction:(UIButton*)sender{
    
    if (self.segment.selectedSegmentIndex == 0) {
        FindModel *find = self.topicArray[_topicArray.count-sender.tag+1000];
        [[SKXRongCloudManager sharaManager] playRecordSuccessWithURL:find.messageVoice];
    }else if (self.segment.selectedSegmentIndex == 1){
        
        FindModel *find = self.myCollectArray[_myCollectArray.count - sender.tag + 500];
         [[SKXRongCloudManager sharaManager] playRecordSuccessWithURL:find.messageVoice];
    }else{
        
        ReplyModel *model = self.replayArray[self.replayArray.count - sender.tag + 2000];
        [[SKXRongCloudManager  sharaManager] playRecordSuccessWithURL:model.replyVoice];
    
    }
    
}


//点击头像跳转
- (void)ClickUserPictureBtn:(UIButton*)sender{
    
    PersonalHomePageTableViewController *perVC = [[PersonalHomePageTableViewController alloc]init];
    
    if (self.segment.selectedSegmentIndex == 0) {
        perVC.model = self.topicArray[_topicArray.count-sender.tag+1000];
        NSLog(@"这是TopicTableViewCell子控件的点击事件");
        [self.navigationController pushViewController:perVC animated:YES];

    }else if (self.segment.selectedSegmentIndex == 1){
        
        perVC.model = self.myCollectArray[_myCollectArray.count - sender.tag + 500];
        NSLog(@"这是TopicTableViewCell子控件的点击事件");
        [self.navigationController pushViewController:perVC animated:YES];

    }else{
        
//        perVC.modelType = @"replyModel";
        perVC.model = self.topicArray[_topicArray.count-sender.tag+2000];
        NSLog(@"这是TopicTableViewCell子控件的点击事件");
        [self.navigationController pushViewController:perVC animated:YES];

    }
    
}

//cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //根据segment的下标选择不同高度 满足需要
    if (self.index == 2) {
        
        return self.view.frame.size.height/3.7;
        
    }else{
        
        return [self tableView:tableView cellForRowAtIndexPath:indexPath].height;

    }
}

//cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"你点击了ClickRightCornerJumpToViewController中的cell");
    NSLog(@"即将跳转到的页面是:发现 ——> ReplyViewController");
    
    ReplyViewController*replyVC = [[ReplyViewController alloc]init];
    
    if (self.segment.selectedSegmentIndex == 2) {
        
        return;
        
    }else if (self.segment.selectedSegmentIndex == 1){
        
          replyVC.findModel = self.myCollectArray[self.myCollectArray.count-1-indexPath.row];
         [self.navigationController pushViewController:replyVC animated:YES];
    }else{
        
         replyVC.findModel = self.topicArray[self.topicArray.count-1-indexPath.row];

         [self.navigationController pushViewController:replyVC animated:YES];
    }
    
}

@end
